﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.IO;


//to do
//config x264 setting(test needed)
//audio delay(test needed)(now disabled)
//update job status outside this program may cause conflict exception(wont't fix)
//support 0 target size, use target size list with max/min/prefer bitrate limit
//copy mkv file to avoid disk fragments
//support resource cost job allocate
//support force job start
namespace AutoEncodeDaemon
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [MTAThread]
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));
            if (args.Count() == 2)
            {
                try
                {
                    if (args[1].Contains(Properties.Settings.Default.TorrentJobPath) == false) return;
                    AutoEncodeDBContext db = new AutoEncodeDBContext();
                    db.AddTorrentJob(args[0], args[1].Replace("\"", ""));
                }
                catch (Exception ex)
                {
                    AutoEncodeLog.Log2File(String.Format("Encountered an error(\"{0}\") while adding TorrentJob(Name: \"{1}\" Path: \"{2}\") to database ", ex.ToString(), args[0], args[1].Replace("\"", "")));
                }
                return;
            }
            if (args.Count() == 1 && args[0] == "/config")
            {
                Application.Run(new Config());
                return;
            }
            bool ok;
            Semaphore s = new Semaphore(0, 1, "AutoEncodeDaemon", out ok);
            if (args.Count() == 1 && args[0] == "/viewdb")
            {
                if (ok)
                {
                    AutoEncodeDBContext db = new AutoEncodeDBContext();
                    Application.Run(new Viewer(db));
                }
                else
                {
                    s.Release();
                }
                return;
            }
            if (!ok)
            {
                AutoEncodeLog.Log2File("AutoEncodeDaemon is already started");
                return;
            }
            JobScheduler scheduler = new JobScheduler(s);
            AutoEncodeLog.Log2File("Scheduler is running...");
            scheduler.Run();
            GC.KeepAlive(s);
        }
    }
}
